'use strict';

const path = require('path');
const _ = require('lodash');
const { Service, Storage } = require('ee-core');
const express = require('express');
const router = express.Router(); // 可以使用路由拆分路由
const bodyParser = require('body-parser'); //处理程序之前，在中间件中对传入的请求体进行解析（response body）
const cors = require('cors'); //服务器端跨域处理
const axios = require('axios');
const cookieParser = require('cookie-parser');
const createError = require('http-errors');

const app = express();
const HOST = 'http://127.0.0.1';
const PORT = 10010;

app.use(express.json()); //数据json化
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser()); //cookie处理中间价
app.use(bodyParser.json()); //请求体解析
app.use(cors()); //跨域处理

class LocalService extends Service {
  constructor(ctx) {
    super(ctx);
  }

  start() {
    this.generRouter();
    app.listen(PORT, () => {
      console.log(`server is running on  http://${HOST}:${PORT}`);
    });

    return '开启成功';
  }

  end() {
    console.log('hello world');
  }

  generRouter() {
    // test demo
    app.use('/chp', async (req, res, next) => {
      const result = await axios.get('https://api.shadiao.pro/chp');
      res.json({ code: 1, data: result.data });
    });

    /**
     * @desc 获取所有task
     */
    app.use('/all', async (req, res, next) => {
      const data = await this.app.service.localServiceStorage.getAllTaskDataSqlite();
      res.json({
        code: 1,
        data,
      });
    });

    app.use('/single', async (req, res, next) => {
      console.log(req.query);
      let id = req.query.id || null;
      if (!id) {
        res.json({
          code: 2,
          error: '缺少必要参数',
        });
      } else {
        const data = await this.app.service.localServiceStorage.getSingleTaskData(id);
        res.json({
          code: 1,
          data,
        });
      }
    });

    app.use('/deltask', async (req, res, next) => {
      console.log(req.query);
      let id = req.query.id || null;
      if (!id) {
        res.json({
          code: 2,
          error: '缺少必要参数',
        });
      } else {
        const data = await this.app.service.localServiceStorage.delTaskDataSqlite(id);
        res.json({
          code: 1,
          msg: data ? '删除成功' : '删除失败',
        });
      }
    });

    app.use('/update', async (req, res, next) => {
      let { id, progress } = req.query;
      if (!id) {
        res.json({
          code: 2,
          error: '缺少必要参数',
        });
      } else {
        const data = await this.app.service.localServiceStorage.updateTaskDataSqlite(id, progress);
        res.json({
          code: 1,
          msg: '更新成功',
        });
      }
    });

    // 未匹配404处理
    app.get('*', (req, res) => {
      res.status(404).send(createError(404));
    });
  }
}

LocalService.toString = () => '[class LocalService]';
module.exports = LocalService;
